package com.xinchuang.service.targetSystem.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultEnum;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.mapper.targetSystem.*;
import com.xinchuang.entity.targetSystem.Zone;
import com.xinchuang.entity.targetSystem.object.SystemDataAdd;
import com.xinchuang.entity.targetSystem.system.*;
import com.xinchuang.entity.targetSystem.target.TargetData;
import com.xinchuang.mapper.targetSystem.external.TargetExternalMapper;
import com.xinchuang.service.targetSystem.KnowService;
import com.xinchuang.service.targetSystem.SystemBuildService;
import com.xinchuang.util.RedisUtil;
import com.xinchuang.util.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * @ClassName TargetSystemServiceImpl
 * @Description:
 * @auther xukl
 * @data 2021/3/25  11:30
 * @Version V1.0
 */
@Service(value = "systemBuildService")
public class SystemBuildServiceImpl implements SystemBuildService {

    @Resource
    private SystemMasterMapper system;

    @Resource
    private KeyWordSystem keyWordSystem;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TargetMapper targetMapper;

    @Resource
    private SystemsMasterMapper systemsMasterMapper;

    @Resource
    private TargetExternalMapper target;

    @Resource
    private KnowService knowService;

    @Resource
    private ZoneMapper zoneMapper;

    @Resource
    private IdeaMapper ideaMapper;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);

    @Override
    public Result selectSystemList(int pageNum, int pageSize, List<String> typeList, String keyword) {
        if (StringUtils.isBlank(keyword)) {
            keyword = null;
        }
        if (null == typeList || typeList.isEmpty()) {
            typeList = null;
        } else {
            List<String> list = targetMapper.selectTargetTypeNames(typeList);
            if (CollectionUtil.isNotEmpty(list)) {
                typeList = list;
            } else {
                typeList = null;
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<SystemMaster> list = system.selectSystemList(typeList, keyword);
        PageInfo<SystemMaster> pageInfo = new PageInfo<>(list);
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (SystemMaster systemMaster : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("sId", systemMaster.getSId());
                map.put("systemName", systemMaster.getSystemName());
                map.put("targetType", systemMaster.getTargetType());
                map.put("include", systemMaster.getInclude());
                map.put("icon", StringUtils.isNotBlank(systemMaster.getIcon()) ? this.keyWordSystem.getSERVER_URL() + systemMaster.getIcon() : null);
            }
        }
        resultMap.put("systemList", resultList);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result selectSystemOnly(String sId, String systemName, String targetType, String country, String remark, String sysType, String url) {
        String key = this.keyWordSystem.getVERSION() + "system" + sId;
        String infoKey = this.keyWordSystem.getVERSION() + "info" + sId;
        String targetTypeKey = this.keyWordSystem.getVERSION() + "targetType" + sId;
        String countryKey = this.keyWordSystem.getVERSION() + "country" + sId;
        String oldRelation = this.keyWordSystem.getVERSION() + "oldRel" + sId;
        SystemMaster systemMaster = system.selectSystemOnly(sId);
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNotBlank(country)) {
            redisUtil.set(countryKey, country, KeyWordSystem.REDIS_TIME);
        }
        if (null != systemMaster) {
            if (!redisUtil.hasKey(oldRelation)) {
                List<String> list = system.selectSystemRelationTargetId(systemMaster.getSId());
                if (CollectionUtil.isNotEmpty(list)) {
                    redisUtil.sSet(oldRelation, list.toArray());
                }
            }
            resultMap.put("url", StringUtils.isNotBlank(url) ? url : StringUtils.isNotBlank(systemMaster.getIconUrl()) ? systemMaster.getIconUrl() : "");
            resultMap.put("sId", systemMaster.getSId());
            if (StringUtils.isNotBlank(systemName)) {
                resultMap.put("systemName", systemName);
            } else {
                resultMap.put("systemName", systemMaster.getSystemName());
            }
            if (StringUtils.isNotBlank(targetType)) {
                resultMap.put("targetType", targetType);
            } else {
                resultMap.put("targetType", systemMaster.getTargetType());
            }
            if (StringUtils.isNotBlank(country)) {
                resultMap.put("country", country);
            } else {
                resultMap.put("country", systemMaster.getStat());
                if (StringUtils.isNotBlank(systemMaster.getStat())) {
                    redisUtil.set(countryKey, country, KeyWordSystem.REDIS_TIME);
                }
            }
            if (StringUtils.isNotBlank(remark)) {
                resultMap.put("remark", remark);
            } else {
                resultMap.put("remark", systemMaster.getRemark());
            }
            if (StringUtils.isNotBlank(sysType)) {
                resultMap.put("sysType", sysType);
            } else {
                resultMap.put("sysType", StringUtils.isNotBlank(systemMaster.getUserSign()) ? systemMaster.getUserSign().split("&&").length > 1 ? systemMaster.getUserSign().split("&&")[1] : null : null);
            }
//            if (null != resultMap.get("targetType")) {
//                if (redisUtil.hasKey(targetTypeKey)) {
//                    if (!resultMap.get("targetType").toString().equals(redisUtil.get(targetTypeKey).toString())) {
//                        redisUtil.del(key, infoKey);
//                        redisUtil.set(targetTypeKey, resultMap.get("targetType"), keyWordSystem.REDIS_TIME);
//                        //已选目标放入缓存
//                        updateRedisConfirmTarget(sId, key,false);
//                    } else {
//                        //已选目标放入缓存
//                        updateRedisConfirmTarget(sId, key,true);
//                    }
//                } else {
//                    //已选目标放入缓存
//                    updateRedisConfirmTarget(sId, key,true);
//                    redisUtil.set(targetTypeKey, resultMap.get("targetType"), keyWordSystem.REDIS_TIME);
//                }
//            }
            Set<Map<Object, Object>> infoList = new HashSet<>();
            if (StringUtils.isBlank(targetType) && StringUtils.isNotBlank(systemMaster.getTargetType())) {
                //统计属性
                List<InfoElement> list = system.selectInfoBySId(sId);
                Map<Object, Object> infoMap = new HashMap<>();
                boolean juage = false;
                if (null != list && !list.isEmpty()) {
                    juage = true;
                    for (InfoElement infoElement : list) {
                        infoMap.put(infoElement.getKey(), infoElement.getValue());
                    }
                }
                if (redisUtil.hasKey(infoKey)) {
                    infoMap.putAll(redisUtil.hmget(infoKey));
                }
                //统计属性遍历，验证属性是否被选择
                if (!infoMap.isEmpty()) {
                    for (Map.Entry<Object, Object> entry : infoMap.entrySet()) {
                        Map<Object, Object> hashMap = new HashMap<>();
                        hashMap.put("key", entry.getKey());
                        hashMap.put("value", entry.getValue());
                        if (juage) {
                            for (InfoElement infoElement : list) {
                                if (infoElement.getSign() == 1 && infoElement.getKey().equals(entry.getKey().toString())) {
                                    hashMap.put("sign", 1);
                                    break;
                                }
                            }
                        }
                        if (null == hashMap.get("sign")) {
                            hashMap.put("sign", 0);
                        }
                        infoList.add(hashMap);
                    }
                }
                updateRedisInfoElement(infoMap, infoKey);
            } else if (StringUtils.isNotBlank(targetType)) {
                if (targetType.equals(systemMaster.getTargetType())) {
                    //统计属性
                    List<InfoElement> list = system.selectInfoBySId(sId);
                    Map<Object, Object> infoMap = new HashMap<>();
                    boolean juage = false;
                    if (null != list && !list.isEmpty()) {
                        juage = true;
                        for (InfoElement infoElement : list) {
                            infoMap.put(infoElement.getKey(), infoElement.getValue());
                        }
                    }
                    if (redisUtil.hasKey(infoKey)) {
                        infoMap.putAll(redisUtil.hmget(infoKey));
                    }
                    //统计属性遍历，验证属性是否被选择
                    if (!infoMap.isEmpty()) {
                        for (Map.Entry<Object, Object> entry : infoMap.entrySet()) {
                            Map<Object, Object> hashMap = new HashMap<>();
                            hashMap.put("key", entry.getKey());
                            hashMap.put("value", entry.getValue());
                            if (juage) {
                                for (InfoElement infoElement : list) {
                                    if (infoElement.getSign() == 1 && infoElement.getKey().equals(entry.getKey().toString())) {
                                        hashMap.put("sign", 1);
                                        break;
                                    }
                                }
                            }
                            if (null == hashMap.get("sign")) {
                                hashMap.put("sign", 0);
                            }
                            infoList.add(hashMap);
                        }
                    }
                    updateRedisInfoElement(infoMap, infoKey);
                } else if (redisUtil.hasKey(infoKey)) {
                    Map<Object, Object> infoMap = new HashMap<>();
                    infoMap.putAll(redisUtil.hmget(infoKey));
                    //统计属性遍历，验证属性是否被选择
                    if (!infoMap.isEmpty()) {
                        for (Map.Entry<Object, Object> entry : infoMap.entrySet()) {
                            Map<Object, Object> hashMap = new HashMap<>();
                            hashMap.put("key", entry.getKey());
                            hashMap.put("value", entry.getValue());
                            hashMap.put("sign", 0);
                            infoList.add(hashMap);
                        }
                    }
                }
            }
            resultMap.put("stat", infoList);
        } else {
            resultMap.put("sId", sId);
            resultMap.put("systemName", systemName);
            resultMap.put("targetType", targetType);
            resultMap.put("country", country);
            resultMap.put("remark", remark);
            resultMap.put("sysType", sysType);
            resultMap.put("url", StringUtils.isNotBlank(url) ? url : "");
            if (StringUtils.isNotBlank(targetType)) {
                if (redisUtil.hasKey(targetTypeKey)) {
                    if (!redisUtil.get(targetTypeKey).toString().equals(targetType)) {
                        redisUtil.del(key);
                        redisUtil.del(infoKey);
                        redisUtil.set(targetTypeKey, targetType, KeyWordSystem.REDIS_TIME);
                    }
                } else {
                    redisUtil.set(targetTypeKey, resultMap.get("targetType"), KeyWordSystem.REDIS_TIME);
                }
            }
            //统计属性
            List<Map<Object, Object>> infoList = new ArrayList<>();
            if (redisUtil.hasKey(infoKey)) {
                Map<Object, Object> map = redisUtil.hmget(infoKey);
                for (Map.Entry<Object, Object> objectObjectEntry : map.entrySet()) {
                    Map<Object, Object> hashMap = new HashMap<>();
                    hashMap.put("key", objectObjectEntry.getKey());
                    hashMap.put("value", objectObjectEntry.getValue());
                    hashMap.put("sign", 0);
                    infoList.add(hashMap);
                }
            }
            resultMap.put("stat", infoList);
        }
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result selectSystemWaitTarget(String country, String targetType, String sId, String keyword, int status) {
        if (StringUtils.isBlank(targetType)) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("targetList", new ArrayList<>());
            return ResultUtil.success("查询成功", resultMap);
        }
        String key = this.keyWordSystem.getVERSION() + "system" + sId;
        String targetTypeKey = this.keyWordSystem.getVERSION() + "targetType" + sId;
        String countryKey = this.keyWordSystem.getVERSION() + "country" + sId;
        String old = null;
        String oldC = null;
        if (status == 1) {
            redisUtil.del(key);
        }
        SystemMaster systemMaster = system.selectSystemOnly(sId);
        if (null != systemMaster && StringUtils.isNotBlank(systemMaster.getTargetType())) {
            old = systemMaster.getTargetType();
        }
        if (null != systemMaster && StringUtils.isNotBlank(systemMaster.getStat())) {
            oldC = systemMaster.getStat();
        }
        String redisCountry = null;
        if (redisUtil.hasKey(countryKey) && null != redisUtil.get(countryKey)) {
            redisCountry = redisUtil.get(countryKey).toString();
        }
        String redisTarget = null;
        if (redisUtil.hasKey(targetTypeKey) && null != redisUtil.get(targetTypeKey)) {
            redisTarget = redisUtil.get(targetTypeKey).toString();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //首次查询系统，初始化国家及类型
        if (status == 1) {
            if (StringUtils.isNotBlank(old)) {
                redisUtil.set(targetTypeKey, old, KeyWordSystem.REDIS_TIME);
            }
            if (StringUtils.isNotBlank(oldC)) {
                redisUtil.set(countryKey, oldC, KeyWordSystem.REDIS_TIME);
            }
            updateRedisConfirmTargetCountry(sId, StringUtils.isNotBlank(oldC) ? oldC : null, key, true);
        } else {
            boolean update = false;
            boolean updateC = false;
            //重新选择目标类型，初始化目标列表
            if (null != redisTarget && !targetType.equals(redisTarget)) {
                redisUtil.del(key);
                redisUtil.set(targetTypeKey, targetType, KeyWordSystem.REDIS_TIME);
                if (null != old && old.equals(targetType)) {
                    update = true;
                }
            }
            //重新选择国家，初始化目标列表
            if (null == redisCountry && StringUtils.isNotBlank(country)) {
                redisUtil.del(key);
                redisUtil.set(countryKey, country, KeyWordSystem.REDIS_TIME);
            } else if (null != redisCountry && StringUtils.isBlank(country)) {
                redisUtil.del(key, countryKey);
                if (null == oldC) {
                    update = true;
                }
            } else if (null != redisCountry && !country.equals(redisCountry)) {
                redisUtil.del(key);
                redisUtil.set(countryKey, country, KeyWordSystem.REDIS_TIME);
            } else if (StringUtils.isNotBlank(oldC) && StringUtils.isNotBlank(country)) {
                if (update) {
                    updateC = true;
                }
            }
            //更新数据
            if (updateC) {
                updateRedisConfirmTargetCountry(sId, country, key, true);
            } else if (update) {
                updateRedisConfirmTarget(sId, key, true);
            }
        }
//        if (StringUtils.isNotBlank(country)) {
//            if (status == 1) {
//                redisUtil.del(key);
//                countryUpdate = true;
//            } else if (null != redisCountry && !country.equals(redisCountry)) {
//                redisUtil.del(key);
//                countryDelete = true;
//                redisUtil.set(countryKey, country, keyWordSystem.REDIS_TIME);
//            } else if (null != oldC && oldC.equals(country)) {
//                countryUpdate = true;
//            } else if (null != redisCountry && country.equals(redisCountry)) {
//                countryUpdate = true;
//            } else if (null == redisCountry) {
//                redisUtil.del(key);
//            }
//        } else if (null == oldC) {
//            if (status == 1) {
//                countryUpdate = true;
//            } else if (null == redisCountry){
//                countryDelete = true;
//            }
//        }
//        if (StringUtils.isNotBlank(targetType)) {
//            if (redisUtil.hasKey(targetTypeKey)) {
//                if (null != old && targetType.equals(redisUtil.get(targetTypeKey).toString())) {
//                    //已选目标放入缓存
//                    if (countryUpdate) {
//                        updateRedisConfirmTargetCountry(sId, StringUtils.isNotBlank(country) ? country : null, key, true);
//                    } else {
//                        if (!countryDelete) {
//                            updateRedisConfirmTarget(sId, key, true);
//                        }
//                    }
//                } else if (!targetType.equals(redisUtil.get(targetTypeKey).toString())) {
//                    redisUtil.del(key);
//                }
//                redisUtil.set(targetTypeKey, targetType, keyWordSystem.REDIS_TIME);
//            } else {
//                if (null != old && !old.equals(targetType)) {
//                    redisUtil.del(key);
//                } else if (null != old && old.equals(targetType)) {
//                    //已选目标放入缓存
//                    if (countryUpdate) {
//                        updateRedisConfirmTargetCountry(sId, StringUtils.isNotBlank(country) ? country : null, key, true);
//                    } else {
//                        if (!countryDelete) {
//                            updateRedisConfirmTarget(sId, key, true);
//                        }
//                    }
//                }
//                redisUtil.set(targetTypeKey, targetType, keyWordSystem.REDIS_TIME);
//            }
//        }
        if (StringUtils.isBlank(keyword)) {
            keyword = null;
        }
        if (StringUtils.isBlank(country)) {
            country = null;
        }
        //根据类别查询目标
        Integer level = target.selectTypeLevel(targetType);
        if (null == level) {
            return ResultUtil.error(ResultEnum.TYPE_EMPTY);
        }
        List<String> typeIds = new ArrayList<>();
        typeIds.add(targetType);
        if (level == 1) {
            typeIds.addAll(target.selectSubIdType(targetType));
        }
        //查询已选择的目标
        List<String> targetIds = new ArrayList<>();
        Set<Object> set = null;
        if (redisUtil.hasKey(key)) {
            set = redisUtil.sGet(key);
            for (Object o : set) {
                targetIds.add(o.toString());
            }
        }
//        List<String> confirmTarget = system.selectSystemRelationTargetId(sId);
//        if (null != confirmTarget && !confirmTarget.isEmpty()) {
//            if (null == set) {
//                set = new HashSet<>();
//            }
//            for (String s : confirmTarget) {
//                set.add(s);
//            }
//        }
//        if (null != set) {
//            redisUtil.del(key);
//            redisUtil.sSetAndTime(key, keyWordSystem.REDIS_TIME, set.toArray());
//        }
//        if (targetIds.isEmpty()) {
//            targetIds = null;
//        }
        //省市区查询封装
        if (StringUtils.isNumeric(country)) {
            Zone zone = zoneMapper.getZoneByAdcode(country);
            if (ObjectUtil.isNotEmpty(zone)) {
                if (zone.getLevel().equals("city")) {
                    zone = zoneMapper.getZoneByAdcode(country);
                    List<Zone> zones = zoneMapper.getZoneByParent(zone.getAdcode());
                    if (CollectionUtil.isNotEmpty(zones)) {
                        for (Zone z : zones) {
                            country = "[" + "\"" + z.getParent() + "\"" + "," + "\"" + z.getAdcode() + "\"" + "]";
                        }
                    }
                } else if (zone.getLevel().equals("district")) {
                    country = "[" + "\"" + zone.getParent() + "\"" + "," + "\"" + country + "\"" + "]";
                }
            }
        }
        List<TargetData> targetDataList = system.selectWaitChoiceTarget(country, typeIds, null, keyword);
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(targetDataList)) {
            for (TargetData targetData : targetDataList) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("icon", StringUtils.isNotBlank(targetData.getIcon()) ? this.keyWordSystem.getSERVER_URL() + targetData.getIcon() : null);
                if (targetIds.contains(targetData.getTargetId())) {
                    map.put("sign", 1);
                } else {
                    map.put("sign", 0);
                }
                list.add(map);
            }
        }
        resultMap.put("targetList", list);
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result addChoiceTarget(String sId, List<String> targetList, String status) {
        String key = keyWordSystem.getVERSION() + "system" + sId;
//        String infoKey = keyWordSystem.getVERSION() + "info" + sId;
        if (status.equals("add")) {
            //已选目标
            Set<Object> set = new HashSet<>();
            if (redisUtil.hasKey(key)) {
                set = redisUtil.sGet(key);
            }
            for (String s : targetList) {
                set.add(s);
            }
            if (CollectionUtil.isNotEmpty(set)) {
                redisUtil.sSetAndTime(key, KeyWordSystem.REDIS_TIME, set.toArray());
            }
            //统计属性选择
//            List<String> confirmTarget = system.selectSystemRelationTargetId(sId);
//            if (CollectionUtil.isNotEmpty(confirmTarget)) {
//                targetList.addAll(confirmTarget);
//            }
//            Map<String, Object> infoMap = new HashMap<>();
//            List<CommonAttribute> commons = system.findCommonIndex(this.keyWordSystem.INFO);
//            if (null != commons && !commons.isEmpty()) {
//                for (CommonAttribute common : commons) {
//                    infoMap.put(common.getKey(), common.getKeyName() + "(" + common.getKey() + ")");
//                }
//            }
//            for (String s : targetList) {
//                List<SpecialAttribute> specials = system.findSpecialIndex(s, this.keyWordSystem.INFO);
//                if (null != specials && !specials.isEmpty()) {
//                    for (SpecialAttribute special : specials) {
//                        infoMap.put(special.getKey(), special.getKeyName() + "(" + special.getKey() + ")");
//                    }
//                }
//            }
//            //添加原有属性信息
//            if (redisUtil.hasKey(infoKey)) {
//                for (Map.Entry<Object, Object> objectObjectEntry : redisUtil.hmget(infoKey).entrySet()) {
//                    infoMap.put(objectObjectEntry.getKey().toString(), objectObjectEntry.getValue());
//                }
//                redisUtil.del(infoKey);
//            }
//            redisUtil.hmset(infoKey, infoMap, keyWordSystem.REDIS_TIME);
        } else if (status.equals("del")) {
//            SystemMaster systemMaster = system.selectSystemOnly(sId);
//            if (null != systemMaster && CollectionUtil.isNotEmpty(targetList)) {
//                system.deleteSystemRelation(sId, targetList);
//            }
            //清理多余的已选目标
            if (CollectionUtil.isNotEmpty(targetList)) {
                redisUtil.setRemove(key, targetList.toArray());
//                Set<Object> set = redisUtil.sGet(key);
//                if (CollectionUtil.isEmpty(set)) {
//                    if (redisUtil.hasKey(infoKey)) {
//                        redisUtil.del(infoKey);
//                    }
//                }
            }
            //清理多余的统计属性
//            Map<Object, Object> infoMap = new HashMap<>();
//            if (redisUtil.hasKey(infoKey)) {
//                infoMap = redisUtil.hmget(infoKey);
//            }
//            for (String s : targetList) {
//                //查询同类别目标关联数量
//                if (system.selectClassifyCount(s) == 0) {
//                    List<SpecialAttribute> specials = system.findSpecialIndex(s, this.keyWordSystem.INFO);
//                    if (null != specials && !specials.isEmpty()) {
//                        for (SpecialAttribute special : specials) {
//                            infoMap.remove(special.getKey());
//                        }
//                    }
//                }
//            }
//            updateRedisInfoElement(infoMap, infoKey);
        }
        return ResultUtil.success("更新成功", null);
    }

    @Override
    public Result selectSystemConfirmTarget(int pageNum, int pageSize, String sId, String keyword) {
        if (StringUtils.isBlank(keyword)) {
            keyword = null;
        }
        //已选目标
        List<String> targetIds = new ArrayList<>();
        String key = keyWordSystem.getVERSION() + "system" + sId;
        if (redisUtil.hasKey(key)) {
            Set<Object> set = redisUtil.sGet(key);
            for (Object o : set) {
                targetIds.add(o.toString());
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        //判断已选目标
        if (targetIds.isEmpty()) {
            resultMap.put("targetList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetData> targetDataList = system.selectChoiceTarget(targetIds, keyword);
        PageInfo<TargetData> pageInfo = new PageInfo<>(targetDataList);
        List<Map<String, Object>> list = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (TargetData targetData : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("icon", StringUtils.isNotBlank(targetData.getIcon()) ? this.keyWordSystem.getSERVER_URL() + targetData.getIcon() : null);
                list.add(map);
            }
        }
        resultMap.put("targetList", list);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result addSystem(SystemDataAdd systemDataAdd, String userId) {
        //已选目标key
        String key = keyWordSystem.getVERSION() + "system" + systemDataAdd.getSId();
        //统计属性key
//        String infoKey = keyWordSystem.getVERSION() + "info" + systemDataAdd.getSId();
        //已选类型
        String targetTypeKey = this.keyWordSystem.getVERSION() + "targetType" + systemDataAdd.getSId();
        //国家
        String countryKey = this.keyWordSystem.getVERSION() + "country" + systemDataAdd.getSId();
        //关联ID
        String oldRelation = this.keyWordSystem.getVERSION() + "oldRel" + systemDataAdd.getSId();
        system.deleteInfo(systemDataAdd.getSId());
        //目标数量
        int targetNum = 0;
        Set<Object> confirmTarget = new HashSet<>();
        if (StringUtils.isNotBlank(systemDataAdd.getTargetId())) {
            confirmTarget.add(systemDataAdd.getTargetId());
        }
        if (redisUtil.hasKey(key)) {
            confirmTarget.addAll(redisUtil.sGet(key));
        }
        //添加统计属性
//        boolean juage = false;
//        if (null != systemDataAdd.getInfo() && !systemDataAdd.getInfo().isEmpty()) {
//            juage = true;
//        }
//        Map<Object, Object> infoMap = redisUtil.hmget(infoKey);
//        if (null != infoMap && !infoMap.isEmpty()) {
//            Map<String, Object> info = new HashMap<>();
//            for (Map.Entry<Object, Object> objectObjectEntry : infoMap.entrySet()) {
//                info.put(objectObjectEntry.getKey() + "", objectObjectEntry.getValue());
//            }
//            //验证属性是否被选择
//            List<InfoElement> elements = new ArrayList<>();
//            for (Map.Entry<String, Object> objectObjectEntry : info.entrySet()) {
//                InfoElement element = new InfoElement();
//                element.setId(snowflakeIdWorker.nextId() + "");
//                element.setSId(systemDataAdd.getSId());
//                element.setKey(objectObjectEntry.getKey());
//                element.setValue(objectObjectEntry.getValue().toString());
//                element.setSign(0);
//                if (juage) {
//                    for (String s : systemDataAdd.getInfo()) {
//                        if (objectObjectEntry.getKey().equals(s)) {
//                            element.setSign(1);
//                            break;
//                        }
//                    }
//                }
//                elements.add(element);
//            }
//            system.addInfoElement(elements);
//        }
        SystemMaster systemMaster = new SystemMaster();
        systemMaster.setSId(systemDataAdd.getSId());
        systemMaster.setSystemName(systemDataAdd.getSystemName());
        systemMaster.setTargetType(systemDataAdd.getTargetType());
        systemMaster.setInclude(targetNum);
        systemMaster.setRemark(systemDataAdd.getRemark());
        systemMaster.setUserSign((StringUtils.isNotBlank(userId) ? userId : "0") + "&&" + systemDataAdd.getSysType());
        systemMaster.setStat(systemDataAdd.getCountry());
        systemMaster.setIcon(systemDataAdd.getUrl());
        systemMaster.setIconUrl(systemDataAdd.getUrl());
        if (StringUtils.isNotBlank(systemDataAdd.getTargetId())) {
            systemMaster.setTaskSign(systemDataAdd.getTaskId());
        }
        ArrayList<String> oldRelList = new ArrayList<>();
        ArrayList<String> oldRelLists = new ArrayList<>();
        SystemMaster old = system.selectSystemOnly(systemDataAdd.getSId());
        if (null != old) {
            systemMaster.setIcon(old.getIcon());
            systemMaster.setIconUrl(old.getIconUrl());
            systemMaster.setCreateTime(old.getCreateTime());
            if (redisUtil.hasKey(oldRelation)) {
                Set<Object> set = redisUtil.sGet(oldRelation);
                if (CollectionUtil.isNotEmpty(set)) {
                    for (Object o : set) {
                        oldRelList.add(o.toString());
                        oldRelLists.add(o.toString());
                    }
                }
            }
        } else {
            systemMaster.setCreateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }
        system.addSystem(systemMaster);
        //系统关联目标新增
        system.deleteConfirm(systemDataAdd.getSId());
        //清理系统没有目标后残留数据
        if (CollectionUtil.isEmpty(confirmTarget) && CollectionUtil.isNotEmpty(oldRelList)) {
            for (String s : oldRelList) {
                knowService.deleteSystemTargetValue(systemMaster.getSId(), s);
            }
        }
        if (CollectionUtil.isNotEmpty(confirmTarget)) {
            List<String> targrtIds = new ArrayList<>();
            List<SystemRelation> relations = new ArrayList<>();
            for (Object o : confirmTarget) {
                SystemRelation relation = new SystemRelation();
                relation.setSRelId(snowflakeIdWorker.nextId() + "");
                relation.setSId(systemDataAdd.getSId());
                relation.setTargetId(o.toString());
                relations.add(relation);
                targrtIds.add(o.toString());
            }
            targetNum = confirmTarget.size();
            system.addSystemRelation(relations);
            if (CollectionUtil.isNotEmpty(oldRelList)) {
                oldRelList.removeAll(confirmTarget);
                confirmTarget.removeAll(oldRelLists);
            }
            if (CollectionUtil.isNotEmpty(oldRelList)) {
                for (String s : oldRelList) {
                    knowService.deleteSystemTargetValue(systemMaster.getSId(), s);
                }
                ideaMapper.deleteIdeaTargetList(systemMaster.getSId(), oldRelList);
            }
            //为体系新增目标
            if (CollectionUtil.isNotEmpty(confirmTarget)) {
                List<SystemsRelation> list = new ArrayList<>();
                for (Object o : confirmTarget) {
                    if (ObjectUtil.isNotEmpty(o)) {
                        String s = systemsMasterMapper.selectHavaSystemIdSystems(o.toString());
                        String id = systemsMasterMapper.selectSystemsRelationTargetId(s, o.toString());
                        if (StringUtils.isBlank(id)) {
                            SystemsRelation relation = new SystemsRelation();
                            relation.setSysRelId(snowflakeIdWorker.nextId() + "");
                            relation.setSysId(s);
                            relation.setTargetId(s);
                            relation.setTargetType("0");
                            targrtIds.add(s);
                            list.add(relation);
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(list)) {
                    systemsMasterMapper.addSystemsRelation(list);
                }
            }
        }
        redisUtil.del(key, targetTypeKey, countryKey, oldRelation);
//        redisUtil.del(infoKey);
        return ResultUtil.success("系统信息录入成功", null);
    }

    @Override
    public Result selectSystemElseData(String sId) {
        SystemMaster systemMaster = system.selectSystemOnly(sId);
        if (null == systemMaster) {
            return ResultUtil.error(ResultEnum.SYSTEM_IS_EXIST);
        }
        List<SystemElseData> elseData = system.selectSystemElseDataList(sId);
        if (CollectionUtil.isEmpty(elseData)) {
            return ResultUtil.success(new ArrayList<>());
        }
        Map<String, String> resultMap = new HashMap<>();
        for (SystemElseData elseDatum : elseData) {
            resultMap.put(elseDatum.getKey(), elseDatum.getKeyValue());
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result addSystemElseData(String sId, List<SystemElseData> list) {
        if (CollectionUtil.isEmpty(list)) {
            return ResultUtil.error(ResultEnum.SYSTEM_ELSE_NULL);
        }
        SystemMaster systemMaster = system.selectSystemOnly(sId);
        if (null == systemMaster) {
            return ResultUtil.error(ResultEnum.SYSTEM_IS_EXIST);
        }
        for (SystemElseData systemElseData : list) {
            systemElseData.setId(snowflakeIdWorker.nextId() + "");
            systemElseData.setSid(sId);
        }
        system.delSystemElseData(sId);
        system.addSystemElseData(list);
        return ResultUtil.success("数据更新成功", null);
    }

    @Override
    public Result createDoc(String sId, String damage) {
//        if (StringUtils.isBlank(damage)) {
//            return ResultUtil.error(400, "毁伤效果分析,不能为空");
//        }
//        SystemMaster systemMaster = system.selectSystemOnly(sId);
//        if (null == systemMaster) {
//            return ResultUtil.error(ResultEnum.SYSTEM_IS_EXIST);
//        }
//        List<SystemElseData> elseData = system.selectSystemElseDataList(sId);
//        if (CollectionUtil.isEmpty(elseData)) {
//            return ResultUtil.error(400, "功能分析暂未填写");
//        }
//        for (SystemElseData elseDatum : elseData) {
//            if (elseDatum.getKey().equals("external") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "系统结构分析,不能为空");
//            } else if (elseDatum.getKey().equals("structure") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "系统运行分析,不能为空");
//            } else if (elseDatum.getKey().equals("keyValue") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "关键价值分析,不能为空");
//            } else if (elseDatum.getKey().equals("effect") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "系统打击效果分析,不能为空");
//            } else if (elseDatum.getKey().equals("dynamic") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "系统动态划分与管理,不能为空");
//            }
//        }
//        //创建文件路径
//        FileUtil.mkdir(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sId);
//        //删除之前文件
//        FileUtil.del(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sId + File.separator + systemMaster.getSystemName() + ".doc");
//        try {
//            WordBean wordBean = new WordBean(false);
//            wordBean.createNewDocument();
//            wordBean.insertTitle("", -2, "\"" + systemMaster.getSystemName() + "\"" + "系统毁伤分析报告", 1);
//            wordBean.insertTitle("", -4, "1.系统结构分析", 0);
//            wordBean.insertText(getKeyValue("external", elseData));
//            wordBean.insertTitle("", -4, "2.系统运行分析", 0);
//            wordBean.insertText(getKeyValue("structure", elseData));
//            wordBean.insertTitle("", -4, "3.关键价值分析", 0);
//            wordBean.insertText(getKeyValue("keyValue", elseData));
//            wordBean.insertTitle("", -4, "4.系统打击效果分析", 0);
//            wordBean.insertText(getKeyValue("effect", elseData));
//            wordBean.insertTitle("", -4, "5.系统动态划分与管理", 0);
//            wordBean.insertText(getKeyValue("dynamic", elseData));
//            wordBean.insertTitle("", -4, "6.毁伤效果分析", 0);
//            wordBean.insertText(damage);
//            wordBean.save(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sId + File.separator + systemMaster.getSystemName() + ".doc");
//            wordBean.closeDocument();
//            wordBean.close();
//            return ResultUtil.success("报告生成成功", null);
//        } catch (Exception e) {
            return ResultUtil.error(500, "生成文档异常，请稍后重试。");
//        }
    }

    private String getKeyValue(String key, List<SystemElseData> elseData) {
        for (SystemElseData elseDatum : elseData) {
            if (elseDatum.getKey().equals(key)) {
                return elseDatum.getKeyValue();
            }
        }
        return "";
    }

    @Override
    public Result downDoc(String sId) {
        SystemMaster systemMaster = system.selectSystemOnly(sId);
        if (FileUtil.isFile(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sId + File.separator + systemMaster.getSystemName() + ".doc")) {
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("fileUrl", this.keyWordSystem.getSERVER_URL() + "/doc/" + sId + "/" + systemMaster.getSystemName() + ".doc");
            return ResultUtil.success(resultMap);
        } else {
            return ResultUtil.error(400, "请先生成报告");
        }
    }

    @Override
    public boolean judgeSystemName(String sId, String name) {
        String id = system.selectSystemName(name);
        if (StringUtils.isNotBlank(id) && !sId.equals(id)) {
            return true;
        }
        return false;
    }

    /**
     * 更新统计属性
     */
    private void updateRedisInfoElement(Map<Object, Object> infoMap, String infoKey) {
        if (!infoKey.isEmpty()) {
            Map<String, Object> info = new HashMap<>();
            for (Map.Entry<Object, Object> objectObjectEntry : infoMap.entrySet()) {
                info.put(objectObjectEntry.getKey().toString(), objectObjectEntry.getValue());
            }
            if (redisUtil.hasKey(infoKey)) {
                redisUtil.del(infoKey);
            }
            redisUtil.hmset(infoKey, info, KeyWordSystem.REDIS_TIME);
        }
    }

    /**
     * 更新已选目标
     */
    private void updateRedisConfirmTarget(String sId, String key, boolean juage) {
        List<String> targetIds = new ArrayList<>();
        Set<Object> set = new HashSet<>();
        if (redisUtil.hasKey(key)) {
            set = redisUtil.sGet(key);
            for (Object o : set) {
                targetIds.add(o.toString());
            }
        }
        if (juage) {
            targetIds.addAll(system.selectSystemRelationTargetId(sId));
        }
        for (String id : targetIds) {
            set.add(id);
        }
        if (redisUtil.hasKey(key)) {
            redisUtil.del(key);
        }
        if (CollectionUtil.isNotEmpty(set)) {
            redisUtil.sSetAndTime(key, KeyWordSystem.REDIS_TIME, set.toArray());
        }
    }

    /**
     * 更新已选目标
     */
    private void updateRedisConfirmTargetCountry(String sId, String country, String key, boolean juage) {
        List<String> targetIds = new ArrayList<>();
        Set<Object> set = new HashSet<>();
        if (redisUtil.hasKey(key)) {
            set = redisUtil.sGet(key);
            for (Object o : set) {
                targetIds.add(o.toString());
            }
        }
        if (juage) {
            List<String> list = system.selectSystemRelationAndCountryTargetId(sId, country);
            if (StringUtils.isNotBlank(country) && CollectionUtil.isNotEmpty(list)) {
                redisUtil.del(key);
                targetIds.addAll(list);
            } else if (CollectionUtil.isNotEmpty(list)) {
                targetIds.addAll(list);
            }
        }
        for (String id : targetIds) {
            set.add(id);
        }
        if (redisUtil.hasKey(key)) {
            redisUtil.del(key);
        }
        if (CollectionUtil.isNotEmpty(set)) {
            redisUtil.sSetAndTime(key, KeyWordSystem.REDIS_TIME, set.toArray());
        }
    }

}
